package top.infopub.mgr.mkt.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.BidDecisionDto;
import top.infopub.enums.mkt.*;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.exception.FlowProcessException;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.BidCurrencyDomain;
import top.infopub.mgr.mkt.jsonvo.BidDecisionJsonVo;
import top.infopub.mgr.mkt.service.BidDecisionService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.BidCurrencyVo;
import top.infopub.model.mkt.*;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;
import top.infopub.util.UtilTools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BidDecisionServiceImpl extends GenericServiceImpl<BidDecision, String> implements BidDecisionService {

    @Autowired
    private BidDecisionDao bidDecisionDao;

    @Autowired
    private ProjectRiskDao projectRiskDao;

    @Autowired
    private BidInfoDao bidInfoDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private BidReviewDao bidReviewDao;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private BidAnalysisDao bidAnalysisDao;

    @Override
    public GenericDao<BidDecision, String> getDao() {
        return bidDecisionDao;
    }

    @Override
    public Page<BidCurrencyDomain> selectPage(Page<BidCurrencyDomain> page, BidCurrencyVo bidCurrencyVo) throws ParseException {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        //处理时间范围
        if (!StringUtils.isEmpty(bidCurrencyVo.getDates()))
        {
            String[] splitTime = bidCurrencyVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            bidCurrencyVo.setStartDate(format.parse(splitTime[0]));
            bidCurrencyVo.setEndDate(format.parse(splitTime[1]));
        }else{
            bidCurrencyVo.setDates(null);
        }
        return (Page<BidCurrencyDomain>)bidDecisionDao.selectByDomainWhere(bidCurrencyVo);
    }

    @Override
    public BidDecisionJsonVo queryDetailById(String id) {
        BidDecisionJsonVo bidDecJson = new BidDecisionJsonVo();
        //基础信息
        BidDecisionDto bidDec = bidDecisionDao.queryDetailById(id);
        //回报机制映射
        BackMechEnum bme = BackMechEnum.getByCode(bidDec.getBackMech());
        if (bme != null) {
            bidDec.setBackMech(bme.getName());
        }
        bidDecJson.setInfo(bidDec);

        //项目风险信息
        bidDecJson.setRiskTable(projectRiskDao.selectByProCode(bidDec.getProCode()));

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(bidDec.getProCode(), ProjectFileTypeEnum.FILE_TYPE16.getCode(), null);
        bidDecJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return bidDecJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo editDetail(ProjectInfo proInfo, BidDecision bidDecision, BidInfo bidInfo, List<ProjectAttachment> attachmentList, AuthorizationVO vo, Integer submitType) {
        //根据pro_code查询项目基础信息
        ProjectInfo tmpProInfo = projectInfoDao.findByProCode(bidDecision.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");
        BidInfo tmpBidInfo = bidInfoDao.queryByProCode(bidDecision.getProCode());
        if (tmpBidInfo == null) return RspVo.getFailureResponse(400, "投标信息不存在");
        BidDecision tmpBd = bidDecisionDao.selectByPrimaryKey(bidDecision.getId());
        if (tmpBd == null) return RspVo.getFailureResponse(400, "投标决策不存在");
        //判断审批状态
        if (StringUtils.isNotBlank(tmpBd.getProcessStatus())
                && StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpBd.getProcessStatus())) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }

        //如果审批状态为已完成(9)，只更新是否投标决策
        if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpBd.getProcessStatus())) {
            if (StringUtils.isNotBlank(tmpBd.getIsDecBid())
                    && StringUtils.equals(YesOrNoEnum.NO.getCode(), tmpBd.getIsDecBid())) {
                throw new FlowProcessException("该项目已终止");
            }
            List<BidReview> brList = bidReviewDao.queryByProCode(tmpBd.getProCode());
            if (brList != null && brList.size() > 0) throw new FlowProcessException("该项目已进入后续流程，无法编辑");
            next(tmpBd, bidDecision, vo, tmpProInfo, tmpBidInfo);
            return RspVo.getSuccessResponse();
        }
        //驳回有两种
        //1.投标决策信息被驳回
        //2.是否投标决策选择否被驳回
        if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS10.getCode(), tmpBd.getProcessStatus())) {
            if (StringUtils.isNotBlank(tmpBd.getIsDecBid())
                    && (StringUtils.equals(YesOrNoEnum.NO.getCode(), tmpBd.getIsDecBid())
                    || StringUtils.equals(YesOrNoEnum.YES.getCode(), tmpBd.getIsDecBid()))) {
                //这里为是否通过资格预审选择否被驳回走的流程
                List<BidReview> brList = bidReviewDao.queryByProCode(tmpBd.getProCode());
                if (brList != null && brList.size() > 0) throw new FlowProcessException("该项目已进入后续流程，无法编辑");
                next(tmpBd, bidDecision, vo, tmpProInfo, tmpBidInfo);
                return RspVo.getSuccessResponse();
            }
        }

        proInfo.setId(tmpProInfo.getId());
        proInfo.setUptBy(vo.getId());
        proInfo.setUptTime(new Date());
        //查询的时候映射了文字，该字段不修改
        proInfo.setBackMech(null);
        proInfo.setCarryOrg(null);
        //更新项目基础信息
        projectInfoDao.modifyProjectInfoBySeletive(proInfo);

        //更新投标决策信息
        bidDecision.setUptBy(vo.getId());
        bidDecision.setUptTime(new Date());
        bidDecisionDao.modifyById(bidDecision);

        //更新投标信息
        bidInfo.setId(tmpBidInfo.getId());
        bidInfo.setUptBy(vo.getId());
        bidInfo.setUptTime(new Date());
        bidInfoDao.modifyById(bidInfo);

        //更新附件信息
        projectAttachmentDao.deleteByWhere(proInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE16.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType == 1) {
            //处理OA待办信息
            if (StringUtils.isNotBlank(tmpBd.getOaId())) {
                oaFlowService.finishOA(tmpBd.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(bidDecision.getId()));
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE7, detailJson, bidDecision.getId(), bidDecision.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public void insertRiskTable(List<ProjectRisk> riskTable) {
        bidDecisionDao.insertRiskTable(riskTable);
    }

     public void next(BidDecision tmpBd, BidDecision bidDecision, AuthorizationVO vo,
                      ProjectInfo tmpProInfo, BidInfo tmpBidInfo) {
         BidDecision uptBidDec = new BidDecision();
         uptBidDec.setId(tmpBd.getId());
         uptBidDec.setIsDecBid(bidDecision.getIsDecBid());
         uptBidDec.setUptBy(vo.getId());
         uptBidDec.setUptTime(new Date());
         bidDecisionDao.modifyById(uptBidDec);
         if (StringUtils.equals(YesOrNoEnum.NO.getCode(), bidDecision.getIsDecBid())) {
             //是否投标决策选择否，发起项目终止流程
             String detailJson = JSON.toJSONString(queryDetailById(tmpBd.getId()));
             proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE22, detailJson, tmpBd.getId(), tmpBd.getProCode(), vo);
             //处理OA待办信息
             if (StringUtils.isNotBlank(tmpBd.getOaId())) {
                 oaFlowService.finishOA(tmpBd.getOaId());
             }
         } else if (StringUtils.equals(YesOrNoEnum.YES.getCode(), bidDecision.getIsDecBid())) {
             //投标决策，选择是，往标书评审写入数据，并给营销经理发送OA待办
             BidAnalysis bidAnalysis = bidAnalysisDao.queryByProCode(tmpBd.getProCode());
             if (bidAnalysis == null) throw new FlowProcessException("获取不到对应的招标文件分析数据~");
             List<BidReview> list = new ArrayList<>();
             BidReview bidReview;
             for (int i = 1; i <= 3; i++) {
                 if (StringUtils.equals(bidAnalysis.getIsCredit(), "0") && i == 1) continue;
                 if (StringUtils.equals(bidAnalysis.getIsTechnology(), "0") && i == 3) continue;
                 bidReview = new BidReview();
                 bidReview.setCode(IdFactory.getUUIDUpper());
                 bidReview.setProCode(tmpBd.getProCode());
                 bidReview.setBidType(String.valueOf(i));
                 bidReview.setInvestEndTime(tmpBidInfo.getBidEndDate());
                 bidReview.setWillApplyMeetTime(tmpBd.getIntentionMeetTime());
                 bidReview.setProManagers("");
                 bidReview.setAddBy(vo.getId());
                 bidReview.setAddTime(new Date());
                 bidReview.setUptBy(vo.getId());
                 bidReview.setUptTime(new Date());
                 bidReview.setProcessId("-1");
                 bidReview.setProcessStatus("0");
                 list.add(bidReview);
             }
             bidReviewDao.insertBatch(list);
             //查询新增的标书评审列表给营销经理发送OA待办
             List<BidReview> newBrList = bidReviewDao.queryByProCode(tmpBd.getProCode());
             String oaTitle;
             for (BidReview br : newBrList) {
                 if (br == null) continue;
                 String oaId = null;
                 if (StringUtils.equals("1", br.getBidType())) {
                     //资信标
                     oaTitle = UtilTools.getMktOaTitle(tmpProInfo, ProProcessDetailTypeEnum.PRO_NODE_TYPE15);
                     oaId = oaFlowService.sendOAToDo(oaTitle, vo.getId(), tmpProInfo.getAddBy(), FlowTemplateEnum.MKT_BID_REVIEW_ZX.getSrcBizTable(), br.getId());
                 } else if (StringUtils.equals("2", br.getBidType())) {
                     //商务标
                     oaTitle = UtilTools.getMktOaTitle(tmpProInfo, ProProcessDetailTypeEnum.PRO_NODE_TYPE9);
                     oaId = oaFlowService.sendOAToDo(oaTitle, vo.getId(), tmpProInfo.getAddBy(), FlowTemplateEnum.MKT_BID_REVIEW_SW.getSrcBizTable(), br.getId());
                 } else if (StringUtils.equals("3", br.getBidType())) {
                     //技术标
                     oaTitle = UtilTools.getMktOaTitle(tmpProInfo, ProProcessDetailTypeEnum.PRO_NODE_TYPE16);
                     oaId = oaFlowService.sendOAToDo(oaTitle, vo.getId(), tmpProInfo.getAddBy(), FlowTemplateEnum.MKT_BID_REVIEW_JS.getSrcBizTable(), br.getId());
                 }
                 if (StringUtils.isNotBlank(oaId)) {
                     bidReviewDao.modifyOaIdById(oaId, br.getId());
                 }
             }
             //处理OA待办信息
             if (StringUtils.isNotBlank(tmpBd.getOaId())) {
                 oaFlowService.finishOA(tmpBd.getOaId());
             }
         }
     }
}
